package com.itheima.userdemo.service;

import com.itheima.userdemo.mapper.UserMapper;
import com.itheima.userdemo.pojo.User;
import com.itheima.userdemo.utils.SqlSessionFactoryUtils;
import org.apache.ibatis.session.SqlSession;

/**
 * 用户业务类，用户登录、注册，用户列表展示
 */
public class UserService {
    // 查找用户，查询用户

    /**
     * 查找用户，查询用户,Servlet传递参数给service
     * @param username
     * @param password
     * @return
     */
    public User findUserByUsernamePassword(String username, String password){
        // 调用Mapper对象
        // 1.获取SqlSession
        SqlSession sqlSession = SqlSessionFactoryUtils.getSqlSessionFactory().openSession();
        // 2.获取Mapper对象
        UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
        // 3.调用mapper方法
        User user = userMapper.select(username, password);
        System.out.println("UserService select user:"+user);
        return user;
    }

    /**
     * 用户注册
     * @param user 用户信息（从servlet传过来的）
     * @return
     */
    public boolean register(User user){
        // 1. 获得SqlSession,true默认提交事务
        SqlSession sqlSession = SqlSessionFactoryUtils.getSqlSessionFactory().openSession(true);
        // 2. 获得Mapper
        UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
        // 3. 查询用户,根据用户名去查询数据库
        User dbUser = userMapper.selectByUsername(user.getUsername());
        // 4. 判断
        boolean isOk = true;
        if(dbUser != null){
            // 不能注册,注册失败
            isOk = false;
        }else{
            // 可以注册
            Integer addTag = userMapper.add(user);
            isOk = addTag>0 ? true : false;
        }
        // 关闭sqlsession
        sqlSession.close();
        return isOk;
    }
}
















